import { downloadFile, downloadFileAsBase64, saveFile } from "@/utils/file";

export async function getImageUrl(image: string) {
  let avatarPath;
  // #ifndef APP || APP-PLUS
  const avatarBase64 = await downloadFileAsBase64(image);
  avatarPath = avatarBase64;
  // #endif

  // #ifdef APP || APP-PLUS
  const file = await downloadFile(image);
  const tempFilePath = await compressImage(file, 50);
  const filePath = await saveFile(tempFilePath);
  avatarPath = filePath;
  // #endif
  return avatarPath;
}

export async function getTempUrl(image: string) {
  let avatarPath;
  // #ifndef APP || APP-PLUS
  const avatarBase64 = await downloadFileAsBase64(image);
  avatarPath = avatarBase64;
  // #endif

  // #ifdef APP || APP-PLUS
  const file = await downloadFile(image);
  const tempFilePath = await compressImage(file, 50);
  avatarPath = tempFilePath;
  // #endif
  return avatarPath;
}

export async function compressImage(
  image: string,
  quality: number = 50
): Promise<string> {
  if (quality < 0 || quality > 100) {
    throw new Error("quality must be between 0 and 100");
  }
  if (image.startsWith("data:image")) {
    return image;
  }
  if (image.startsWith("http")) {
    return image;
  }
  return new Promise(async (resolve, reject) => {
    // #ifndef H5
    uni.compressImage({
      src: image,
      quality: quality,
      success: (res) => {
        resolve(res.tempFilePath);
      },
    });
    // #endif
    // #ifdef H5
    const path = await translate(image, quality / 100);
    resolve(path);
    // #endif
  });
}

function translate(imgSrc: string, scale: number): Promise<string> {
  //imgSrc:图片的路径
  //scale:缩放比例 0-1之间
  return new Promise((reslove, reject) => {
    var img = new Image(); //创建Image对象生成一个<img>标签
    img.src = imgSrc; //将图片路径赋给<img>标签的src
    img.onload = () => {
      //onload在图片加载成功后触发，在onload中完成压缩功能
      var h = img.height / 2; // 获取原本图片的宽高
      var w = img.width / 2; //默认按比例压缩,根据需求修改
      var canvas: any = document.createElement("canvas"); //创建画布
      var ctx = canvas.getContext("2d"); //设置为2d效果
      var width = document.createAttribute("width"); //创建属性节点
      width.nodeValue = w.toString(); //设置属性值
      var height = document.createAttribute("height");
      height.nodeValue = h.toString();
      canvas.setAttributeNode(width); //设置画布宽高
      canvas.setAttributeNode(height);
      ctx.drawImage(img, 0, 0, w, h); //将图片贴到画布上
      //img:图片 0,0:粘贴的位置 w,h:粘贴图片的大小
      var base64 = canvas.toDataURL("image/png", scale);
      //'image/png':压缩返回图片的类型 scale:图片质量
      //如果要base64的流，可以直接将结果返回了
      canvas = null; //清除画布
      var blob = base64ToBlob(base64); //需要二进制流调用该方法拿到
      let blobUrl = window.URL.createObjectURL(blob); //blob地址
      reslove(blobUrl);
    };
  });
}
// base64转Blob
function base64ToBlob(base64: string) {
  var arr = base64.split(","),
    mime = arr[0].match(/:(.*?);/)![1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime,
  });
}

export function convertImageToBase64(image: any) {
  let canvas = document.createElement("canvas");
  canvas.width = image.width;
  canvas.height = image.height;
  let ctx: any = canvas.getContext("2d");
  ctx.drawImage(image, 0, 0, image.width, image.height);
  let ext = image.src.substring(image.src.lastIndexOf(".") + 1).toLowerCase();
  let dataURL = canvas.toDataURL("image/" + ext);
  return dataURL;
}
